你可以通过resolve
and 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));
卡兹劳斯基斯 https://stackoverflow.com/a/39649159/1906307建议这样做:
var resolve;
var promise = new Promise(function(fulfill) {
resolve = fulfill;
});
不要这样做!.
当您传递给的回调中发生异常时new Promise
,promise 的规范是这样的,异常将自动转换为promise 拒绝。所以如果有什么事情的话throw Error...
在回调中你会得到自动转换。
如果您保存resolve
回调并将您的逻辑移至您传递给的回调之外new Promise
,那么您就不会获得此自动转换。回调之外抛出的异常将仅在堆栈中向上传递而不被转换为承诺拒绝。这很糟糕,因为它需要您的函数的用户才能使用.catch
抓住被拒绝的承诺and 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!"));
当我在 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!