假设我有以下的承诺:
new Promise((resolve, reject) => {
// Some random conditional
if (today === 'Friday') {
console.log("I'm resolving this thing here");
resolve('taco');
// Should I have a return true or false here?
}
console.log("Code made it past the first resolve");
// Do some other code here, like connect to a database or API or something.
connectToDatabase(function(result){
// result was 'hamburger'
resolve(result);
});
}).then((value) => {
console.log(value);
});
在这个例子中,我得到以下输出:
I'm resolving this thing here
Code made it past the first resolve
taco
因此,在我执行resolve
之后,Promise代码继续执行。在上面的示例中,我不必要地连接到某个数据库或端点或其他东西。显然,忽略了发送resolve
,这很好。但从服务成本的角度来看,连接到数据库和API的成本很高,特别是如果每次发出类似AWS服务的请求时都会花费你的钱。
所以我的问题是,我应该在第一个return true;
之后加入resolve
或其他内容吗?
与reject
类似,我应该在return false
之后加入reject
或(true ??)吗?
new Promise((resolve, reject) => {
someAsyncFunction((err, result) => {
if (err) {
reject(err);
// Should I have a return true or false here or something?
}
// Do something here, like connect to a database or fetch a value from some API endpoint or something.
resolve(result);
});
});
如果我不希望代码在reject
之后执行,我应该返回,是吗?
当我查看各种ES6文档时,我无法找到他们明确表达的任何地方......许多Promise示例通常都会非常简化。
如果我确实遗漏了这些东西,我该怎么回事? true
? false
?还是return resolve('taco');
?
答案 0 :(得分:-3)
基本层面理解承诺如何运作以及何时使用解决,拒绝
function d() {
console.log("D started");
return Promise.reject(new Error("Aborted from D function"));
//return Promise.resolve("Done with D");
}
function c() {
console.log("C Started");
//return Promise.reject(new Error("Aborted from C function"));
//return Promise.resolve("Done with C");
return d().then(result => {
return Promise.resolve(result);
}).catch(err => {
return Promise.reject(new Error(err));
});
}
function b() {
console.log("B Started");
//return Promise.reject(new Error("Aborted from B function"));
return Promise.resolve("Done With B");
}
function a() {
console.log("A started");
return b().then(function(resultb){
console.log("B result:"+resultb);
return c();
}).catch(function(err){
console.log("Error:"+err)
}).then(function(resultc){
console.log("C result:"+resultc)
}).catch(function(err){
console.log("Error:"+err);
});
}
a();