Jul*_* E. 4 javascript node.js promise es6-promise
使用promises时,它们会自动运行而不会被调用.我按照MDN Docs设置它们,并在声明它们时运行,而不会被提示.
var progressPromise = new Promise(function(resolve, reject) {
// Query the DB to receive the ToDo tasks
// inProgress is the tableID
getTasks(inProgress, function(tasks) {
// Check that the list is returned.
console.log("Shouldn't Run Automatically");
if (tasks) {
console.log("This Too Runs Automatically");
resolve(tasks);
} else {
reject("There was a failure, the data was not received");
}
});
});Run Code Online (Sandbox Code Playgroud)
<p>Console Output</p>
<p> Shouldn't Run Automatically </p>
<p> This too runs automatically </p>Run Code Online (Sandbox Code Playgroud)
我已经检查了剩下的代码,只有当我启动应用程序时才会触发promises node index.js
这是设计,还是我的实现错了?如果它是设计的,那么如果你可以将我链接到文档会很棒,因为我无法在其上找到任何内容.
谢谢!
T.J*_*der 10
......并且它们在声明时运行,而不会被提示
你没有"宣布"承诺.new Promise创建一个promise并调用你传递它的执行函数.当你想要启动执行程序所做的工作时(那时就是这样),而不是更晚.
如果你想定义一些会返回一个promise而不是启动它的东西,只需将它放在一个函数中:
function doProgress() {
return new Promise(function(resolve, reject) {
// ...
});
}
Run Code Online (Sandbox Code Playgroud)
...然后在您希望该过程开始时调用它:
var progressPromise = doProgress();
Run Code Online (Sandbox Code Playgroud)
文档: