【问题标题】:Node.js Promises Run Without Being CalledNode.js Promises 无需调用即可运行
【发布时间】:2018-04-22 12:34:53
【问题描述】:

使用 Promise 时,它​​们会自动运行而不被调用。我按照 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");
    }
  });

});
<p>Console Output</p>
<p> Shouldn't Run Automatically </p>
<p> This too runs automatically </p>

我检查了剩余的代码,只有当我使用node index.js 启动应用程序时才会触发承诺

这是设计使然,还是我的实现有误?如果它是设计使然,那么如果您可以将我链接到文档,那就太好了,因为我在上面找不到任何东西。

谢谢!

【问题讨论】:

    标签: javascript node.js promise es6-promise


    【解决方案1】:

    ...它们在声明时运行,没有提示

    你没有“宣布”承诺。 new Promise 创建一个 Promise 并在 new Promise 返回之前调用你传递给它的执行器函数,同步。当您希望执行器所做的工作(当时)开始时,您会这样做,而不是稍后。

    如果你想定义一些东西来做一些返回承诺但还没有开始的事情,只需将它放在一个函数中:

    // Explicit promise creation (only when necessary)
    function doProgress() {
        return new Promise(function(resolve, reject) {
            // ...
        });
    }
    
    // Or an `async` function, which always returns a promise
    async function doProgress() {
        // ...code using `await` on other promises/thenables here...
    }
    

    ...然后在您希望该过程开始时调用它:

    var progressPromise = doProgress();
    

    文档:

    【讨论】:

    • FWIW,我还在我最近一本书的第 8 章中深入探讨了 Promise,JavaScript: The New Toys(以及第 9 章中的 async 函数和 await )。如果您有兴趣,请在我的个人资料中链接。
    【解决方案2】:

    你可以在js中这样使用promise

    async function asyncfunc() {
        return new Promise((resolve, reject) => {
            yourFuncWithCallBack((data) => {
                if (data) {
                    resolve(data)
                }
                reject(new Error('data did not exist'))
            });
        });
    }
    

    并像这样使用 asyncFunction

    try {
       var data = await asyncfunc();
       // do some thing with data
    } catch (error) {
     // do some thing with error
    }
    

    如果你想在 typescript 中使用 Promise

    interface ResolveDataType {
       // some property
    }
    
    async function asyncfunc():Promise<ResolveDataType> {
        return new Promise((resolve, reject) => {
            yourFuncWithCallBack((data:ResolveDataType) => {
                if (data) {
                    resolve(data)
                }
                reject(new Error('data did not exist'))
            });
        });
    }
    

    并像这样使用 asyncFunc

    try {
       const data = await asyncfunc();
       // do some thing with data
    } catch (error) {
     // do some thing with error
    }
    

    【讨论】:

      猜你喜欢
      • 2014-07-02
      • 1970-01-01
      • 2018-08-05
      • 1970-01-01
      • 2023-03-25
      • 2012-02-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      相关资源
      最近更新 更多