简体   繁体   English

从函数返回变量和承诺

[英]Return variable and a promise from a function

Consider the following function written using callbacks. 考虑以下使用回调编写的函数。 It returns a token and executes a method asynchronously. 它返回一个令牌并异步执行一个方法。

var token = 1;
function requestSupport(callback) {
  setTimeout(() => {
    console.log(token + ":How may I help you?");
    callback(); //when executive is available
  }, 5000);
  return ++token; //instantly give the token number
}

The ease of callbacks is that the function was able to return the token number (immediately) and also execute code asynchronously and inform when assistance is available. 回调的简便之处在于该函数能够(立即)返回令牌号,并且还可以异步执行代码并在有帮助时发出通知。 What should this function look like when trying to rewrite using Promises? 尝试使用Promises重写时,此函数应该是什么样? PROBLEM: If a function returns a promise, the user won't get the token number as a function can return one thing. 问题:如果一个函数返回一个Promise,则用户将不会获得令牌号,因为一个函数可以返回一件事。

You want to return both the token and the Promise - you can do this with any data structure you want, perhaps an object: 您想同时返回令牌和Promise-您可以使用所需的任何数据结构(可能是一个对象)进行此操作:

 var token = 1; function requestSupportProm() { const prom = new Promise((resolve) => { setTimeout(() => { console.log(token + ":How may I help you?"); resolve(); //when executive is available }, 2000); }); return { prom, token: ++token }; } (() => { // later; const { prom, token } = requestSupportProm(); console.log('Got token:', token); prom.then(() => { console.log('Promise resolved'); }); })(); 

Could also use an array, eg return [prom, ++token] , but the object with named properties will probably be easier to understand at a glance. 也可以使用数组,例如return [prom, ++token] ,但是带有命名属性的对象一目了然可能更容易理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM