如何从承诺中停止函数/返回?

时间:2017-09-29 17:57:32

标签: javascript asynchronous promise return

我想这样做:

function save() {
  //does some stuff here

  somePromise.then(x => {
    //do some stuff here
  }).then(z => {
    //return statement that makes you leave the function
  })
}

我有一个函数,我希望有一个返回,它将在当时完成它的执行,因为我正在使用promises。

非常感谢任何帮助或建议。提前谢谢。

4 个答案:

答案 0 :(得分:1)

使用return

function save() {
  //does some stuff here

  return somePromise.then(x => {
    //do some stuff here
    return /* value */
  }).then(z => {
    //return statement that makes you leave the function
    return /* value */
  })
}

答案 1 :(得分:0)

好的,被视为你的使用承诺。使用promises的最佳功能之一是async / await,大多数现代浏览器现在都内置了这个功能,如果你需要定位旧浏览器,你可以使用像babel这样的东西。

好消息是你可以继续使用带有异步代码的Javascript,就好像它是同步一样,包括for循环/返回/中断......等等。

以下示例..

async function somePromise() {
  console.log('Some promise called');
}

async function earlyReturnTest(doEarly) {
  await somePromise();
  if (doEarly) return;
  console.log('Return not called');
}

async function run() {
  console.log('Without return');
  await earlyReturnTest(false);
  console.log('');
  console.log('With return');
  await earlyReturnTest(true);
}

run();

答案 2 :(得分:-1)

问题是你在then()运行之前已经离开了save()函数。它没有等待它。一种解决方案可能是让您的保存将回调函数作为参数,以便您可以回调正在等待的代码。

function save(callBack) {
  //does some stuff here

  somePromise.then(x => {
    //do some stuff here
  }).then(z => {
    //return statement that makes you leave the function
    callBack();
  })
}

// example of code calling the save
save(function() {
     console.log("save is done running, do something here");
});

答案 3 :(得分:-1)

您可能需要让save函数返回Promise

function save() {
  //does some stuff here
   return new Promise((resolve, reject) => {

  
    somePromise.then(x => {
     resolve("Something1")
    }).then(z => {
      //return statement that makes you leave the function
      resolve("Something2")
    }) 
  
  }
}

save().then(x => {
  console.log(x); // x = something1 || something2
})

相关问题