我想构建一个 Promise,但将解决方案推迟到以后。下面的代码创建了一个承诺,但它立即得到解决。我如何控制承诺何时被评估?
var p = new Promise((resolve, reject) => {
resolve(1);
})
.then((p1) => {
console.log(p1 + 1);
});
Run Code Online (Sandbox Code Playgroud)
更新:为了澄清,想要将承诺的声明与其执行分开的原因是then基于一些参数动态添加回调。
您可以将resolve和传递reject给您想要使用的任何异步函数。并且这样的函数可以在完成其工作时调用它。这是一个在 Node 中运行的示例。如果您运行它,它将ls -l在您的当前目录中执行。该execSomething函数仅接受回调,并且该promiseToExec函数将resolve, reject回调传递给execSomething而不是立即调用它们中的任何一个。
const childProcess = require("child_process");
function execSomething(command, options, onSuccess, onError) {
childProcess.exec(command, options, (err, stdout, stderr) => {
if (err) {
onError(err);
}
onSuccess(stdout, stderr);
});
}
function promiseToExec(command, options) {
return new Promise((resolve, reject) => {
execSomething(command, options, resolve, reject);
});
}
promiseToExec("ls -l").then(console.log.bind(console));
Run Code Online (Sandbox Code Playgroud)
卡兹劳斯基斯建议这样做:
var resolve;
var promise = new Promise(function(fulfill) {
resolve = fulfill;
});
Run Code Online (Sandbox Code Playgroud)
不要这样做!。
当您传递给的回调中发生异常时new Promise,promise 的规范是异常将自动转换为 Promise 拒绝。因此,如果throw Error...回调内发生任何事情,您将获得自动转换。
如果您保存resolve回调并将逻辑移至传递给的回调之外new Promise,则您不会获得此自动转换。回调外部抛出的异常只会在堆栈中向上传递,而不会转换为承诺拒绝。这很糟糕,因为它要求函数的用户用来.catch捕获被拒绝的承诺 和 try...catch抛出的异常。这是一种糟糕的设计实践。
这是说明问题的代码:
// This is how things should be done.
function makeGoodPromise(num) {
return new Promise((resolve) => {
if (num < 0) {
throw new Error("negative num");
}
resolve(num);
});
}
// This is a bad approach because it will sometimes result in synchronous
// exceptions.
function makeBadPromise(num) {
let resolve;
const p = new Promise((fullfil) => {
resolve = fullfil;
});
if (num < 0) {
throw new Error("negative num");
}
resolve(num);
return p;
}
// Shoring up the bad approach with a try... catch clause. This illustrates what
// you need to do convert the exception into a rejection. However, why deal with the
// additional scaffolding when you can just take the simpler approach of not
// leaking the callbacks??
function makeBadPromise2(num) {
let resolve, reject;
const p = new Promise((fullfil, deny) => {
resolve = fullfil;
reject = deny;
});
try {
if (num < 0) {
throw new Error("negative num");
}
resolve(num);
}
catch (e) {
reject(e);
}
return p;
}
makeGoodPromise(-1).catch(() => console.log("caught the good one!"));
try {
makeBadPromise(-1).catch(() => console.log("caught the bad one!"));
}
catch(e) {
console.log("Oops! Synchronous exception: ", e);
}
makeBadPromise2(-1).catch(() => console.log("caught the bad2 one!"));
Run Code Online (Sandbox Code Playgroud)
当我在 Node 中执行它时,这是输出:
Oops! Synchronous exception: Error: negative num
at makeBadPromise (/tmp/t12/test2.js:17:11)
at Object.<anonymous> (/tmp/t12/test2.js:48:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:394:7)
at startup (bootstrap_node.js:149:9)
caught the good one!
caught the bad2 one!
Run Code Online (Sandbox Code Playgroud)
不完全确定您在问什么 - 下面的代码演示了承诺的构造和调用then以相同的顺序发生,但可能在不同的时间执行。wait1更改和的值wait2并查看输出有何不同,但无论时间如何,代码都可以正常工作。
我认为由您来实现承诺代码,以便它等待您想要等待的任何条件。在示例中,它是一个简单的setTimeout,但可以想象您可以采取任何措施来推迟执行。
您可能需要使用 Chrome 才能在浏览器中查看这些结果:
var wait1 = 2000;
var wait2 = 1000;
function log(...str) {
var li = document.createElement('li');
str.forEach((s) => {
li.appendChild(document.createTextNode(s));
});
document.getElementById("log").appendChild(li);
}
var p = new Promise((resolve, reject) => {
setTimeout(() => {
log("Resolving promise!");
resolve(1);
}, wait1);
});
log("Promise created!");
setTimeout(() => {
log("Calling 'then'");
p.then((p1) => {
log("Value:", p1 + 1);
});
}, wait2);Run Code Online (Sandbox Code Playgroud)
<ol id="log" />Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2191 次 |
| 最近记录: |