【问题标题】:How to make async wait for result [duplicate]如何使异步等待结果[重复]
【发布时间】:2021-10-22 02:06:46
【问题描述】:

我有一个这样的课程(简化):

export class Foo {

    constructor(el, menuItems ) {
        this.id = this.el.dataset.id;
        this.menuItems = menuItems;

        this.fetchResult = async function (uri) {

            fetch(uri, {
                method: 'get'
            })
                .then(response => response.json())
                .then(data => {
                    return data.saved === true;
                })
                .catch(function (err) {
                    console.log('Failed ', err);
                    return false;
                });
        }

    }

    doAction(action) {

        const uri  = 'foo/'+ action +'?id=' + this.id;

        const map = {
            'close': async () => {
                const success = await this.fetchResult(action);
                console.log(success); // says undefined? 
            }
            /* some other actions */
        }
        
        return map[action];
    }

    attachDialogs() {
        this.menuItems.addEventListener('click', (element) => {
            this.doAction( element.dataset.action )();
        });
    }    
}

由于某种原因,const success = await this.fetchResult(action); 不等待结果。它立即继续,产生“未定义”值。

在后台进行提取。如何让它等待结果?

【问题讨论】:

  • 尝试使您的 doAction 函数异步,然后在 eventListener 中使用 await 调用它?您的“doAction”函数返回一个异步但函数本身不是异步的函数
  • 你永远不会从fetchResult返回任何东西。您可能还打算将uri 传递给fetchResult,而不是actionMany dupes.

标签: javascript ecmascript-6 async-await


【解决方案1】:

我认为问题在于您没有解决您的请求的响应,请尝试返回一个承诺并仅在您有响应(或错误)时解决

this.fetchResult = function(uri) {
  return new Promise((resolve, reject) => {
    fetch(uri, {
      method: 'get'
    })
    .then(response => response.ok
      ? response.json()
      : reject(new Error(response.statusText)))
    .then(result => resolve(result))
  }
}


const map = {
  'close': async () => {
     const success = await this.fetchResult(action);
   }
}

从 fetchResult 中删除异步是没有理由的。你在 fetchResult 中等待 Promise 的结果,如果 fetch 结果也写在 async await 中,你只需要 async 关键字:

await res = fetch(url)

【讨论】:

    【解决方案2】:

    感谢@Toto Nabendo 和@ggorlen!

    工作解决方案:

    export class Foo {
    
        constructor(el, menuItems ) {
            this.id = this.el.dataset.id;
            this.menuItems = menuItems;
    
            this.fetchResult = async function (uri) {
    
                return fetch(uri, {
                    method: 'get'
                })
                    .then(response => response.json())
                    .then(data => {
                        return data.saved === true;
                    })
                    .catch(function (err) {
                        console.log('Failed ', err);
                        return false;
                    });
            }
    
        }
    
        async doAction(action) {
    
            const uri  = 'foo/'+ action +'?id=' + this.id;
    
            const map = {
                'close': async () => {
                    const success = await this.fetchResult(action);
                    console.log(success);  
                }
                /* some other actions */
            }
            
            return map[action];
        }
    
        attachDialogs() {
            this.menuItems.addEventListener('click', (element) => {
                this.doAction( element.dataset.action )();
            });
        }    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 2020-05-12
      • 1970-01-01
      • 1970-01-01
      • 2018-09-02
      • 2016-12-05
      相关资源
      最近更新 更多