如何从外部函数解析 JS 承诺?

nac*_*n f 1 javascript promise

我有一个 JS 承诺,里面有一个异步函数。如何从异步函数内部解析或拒绝该函数?这是一个示例代码...

    let promise = new Promise(function (resolve, reject) {

        asynchronousFunction();

      }).then(function (response) {
        //...
      });

   function asynchronousFunction() {

    //mimic asynchronous action...
    setTimeout(function(){
     resolve()
    },1000)

  }
Run Code Online (Sandbox Code Playgroud)

Mar*_*yer 5

您的异步函数需要某种方式让外部世界知道它何时需要报告。一些异步函数需要回调。如果是这种情况,您可以传递一个回调来调用您的承诺resolve()

let promise = new Promise(function(resolve, reject) {
  asynchronousFunction((val) => { // < -- pass a callback into the function
    resolve(val)
  });
}).then(function(response) {
  console.log("recieved: ", response)
});

function asynchronousFunction(cb) {
  //mimic asynchronous action...
  setTimeout(function() {
    cb("some return value") // <-- call the callback here withthe return value
  }, 1000)

}
Run Code Online (Sandbox Code Playgroud)

如果你控制了 async 函数,你应该让它直接返回一个 promise:

function asynchronousFunction() {
  //mimic asynchronous action...
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve("some return value")  withthe return value
    }, 1000)
  })
}

// call it:
asynchronousFunction()
  .then(val => console.log(val))
Run Code Online (Sandbox Code Playgroud)