简体   繁体   English

如何在 Javascript 中的 Class 之外返回 Promise 的值

[英]How to Return the Value of a Promise outside a Class in Javascript

I have 2 classes.我有2节课。 One that sets up a promise and another one that gets the result of the promise.一个设置 promise,另一个获得 promise 的结果。

Food食物

export class Food  {
  constructor(initialSettings) {
    super(initialSettings);
    this.foodList = initialSettings.foodListInfo;
  } 

  getFoodListCodes() {
    return Promise.resolve(this.foodList.codes)
  }

  getFoodCode(code){
    return this.getFoodListCodes().then(response => {
     const theResponse = response;
     return theResponse[code]
    })
  }
}

If I were to add a debugger in the Food class, I'm able to confirm that a response is made:如果我要在 Food class 中添加调试器,我可以确认已做出响应: 在此处输入图像描述

Container容器

...
const codeValue = food.getFoodCode(1);

The problem is when I call it in the class above I get a pending promise问题是当我在上面的 class 中调用它时,我得到一个待处理的 promise 在此处输入图像描述 . .

I know the issue is coming from how I'm calling the getFoodCode method.我知道问题出在我调用getFoodCode方法的方式上。 Would I need to call an await in the Container class to get the response?我需要在容器 class 中调用 await 来获得响应吗? Ideally I would like that to be contained in the Food class but I'm not sure if I'm doing it correctly.理想情况下,我希望将其包含在 Food class 中,但我不确定我是否做得正确。

Your function is returning a promise.您的 function 正在返回 promise。 It's not returning the value directly (though it appears you could return it directly).它不是直接返回值(尽管看起来你可以直接返回它)。

The ONLY way for a caller to get a value out of that promise is with .then() or with await .调用者从 promise 中获取值的唯一方法是使用 .then .then()或使用await Those are your two options.这是你的两个选择。

Such as:如:

// this would have to be inside an async function
const codeValue = await food.getFoodCode(1);

or或者

food.getFoodCode(1).then(codeValue => {
     // use codeValue here
     console.log(codeValue);
});

Would I need to call an await in the Container class to get the response?我需要在容器 class 中调用 await 来获得响应吗?

Yes.是的。 Or use .then() .或使用.then()

Ideally I would like that to be contained in the Food class but I'm not sure if I'm doing it correctly.理想情况下,我希望将其包含在 Food class 中,但我不确定我是否做得正确。

You can't.你不能。 Once your operation is promise-based, there's no synchronous way to get the result out and directly return that value.一旦你的操作是基于承诺的,就没有同步的方式来获取结果并直接返回该值。 The caller must use .then() or await to get the value out of the promise.调用者必须使用.then()await从 promise 中获取值。

The promise approach:- promise 方法:-

  getFoodCode(code){
    return this.getFoodListCodes().then(response => {
     const theResponse = response;
     return theResponse[code]
    })
  }

When you are returning from a promise, the result is wrapped inside a promise implicitly and so that's why you are getting a Promise object when calling the method on the object. When you are returning from a promise, the result is wrapped inside a promise implicitly and so that's why you are getting a Promise object when calling the method on the object.

The async/await approach:-异步/等待方法:-

  async getFoodCode(code){
    let theResponse = await this.getFoodListCodes();
    return theResponse[code]
  }

Here also the result is implicitly wrapped in a promise so the same result.这里的结果也隐含在 promise 中,所以结果相同。

Your only way is that you do this operation either by using food.getFoodCode(1).then(.... or await food.getFoodCode(1); inside async function.您唯一的方法是使用food.getFoodCode(1).then(....await food.getFoodCode(1);在异步 function 中执行此操作。

To move getFoodCode() outside your Food class you can do the following:-要将getFoodCode()移到 Food class 之外,您可以执行以下操作:-

const getFoodCode = function(code){
    return this.getFoodListCodes().then(response => {
     // do whatever with the response
    })
  }
getFoodCode.call(food,7);

The only difference is that now getFoodCode is not a property in Food.prototype but rather a function in global scope.唯一的区别是现在getFoodCode不是 Food.prototype 中的属性,而是全局 scope 中的Food.prototype

What I have understood is, you want that specific food object using that code.. and since it returns promise so you need to use.then()我所理解的是,您想要使用该代码的特定食物 object .. 并且由于它返回 promise 所以您需要使用.then()

You can also refer below article: https://dev.to/ramonak/javascript-how-to-access-the-return-value-of-a-promise-object-1bck您还可以参考以下文章: https://dev.to/ramonak/javascript-how-to-access-the-return-value-of-a-promise-object-1bck

fiddle you can check here小提琴你可以在这里查看

JS: JS:

class Food  {
  constructor(initialSettings) {
    this.foodList = initialSettings.foodListInfo;
  } 

  getFoodListCodes() {
    return Promise.resolve(this.foodList);
  }

  getFoodCode(code){
  return this.getFoodListCodes().then((response) => {
      return response[code];
    })
  }
}

var food = new Food({foodListInfo: {1: {name: 'food1'}, 2: {name: 'food2'}, 3: {name: 'food3'}, 4: {name: 'food4'}, 5: {name: 'food5'}}});

var div = document.getElementById('output');
food.getFoodCode(1).then((codeValue) => {
    console.log(codeValue);
    div.innerHTML = codeValue.name;
});

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

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