在JavaScript开关/案例中做出承诺 [英] Making a promise work inside a JavaScript switch/case

查看:98
本文介绍了在JavaScript开关/案例中做出承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题(如果我是诚实的话,那么两个)在转换案例中获得承诺或回调。这是基本代码。

I having a problem (well two if I'm honest) getting a promise or a callback to work inside a switch-case. Here is the basic code.

switch (page) {

  case 'contact':

   alert('contact in switch');

   var promise = $.get(page +'.json');
   promise.then(function(data){
     console.log("Items back! ", data);                     
   });

  break;
  .......

  console.log("Response data: ", data); // This is undefined

据我所知,由于异步功能的性质,交换机正在通过在数据返回之前到 break ,将数据记录为 undefined 。所以我认为在回调中放置 break 会有效,但事实并非如此。当我这样做时,应用程序完全停止工作。

I understand that due to the nature of async functions, the switch is falling through to the break before the data comes back, making data log as undefined. So I thought putting the break inside the callback would work but it doesn't. When I do that the app stops working entirely.

所以我想我的第一个问题是如何让 switch-case 等待直到数据到来回到之前回来

So I guess my first question is how do I make the switch-case "wait" until the data comes back before going to break.

我遇到的第二个问题是我最终希望能够重用我的切换将其包装在一个函数中,其中参数是用户导航到的页面的标题,并且回调将传回从 getPageData 函数返回的数据。当我尝试这个时,它会导致 pageContentLoader 函数的回调出现 undefined 错误。

The second problem I have is that I ultimately want to be able to reuse my switch by wrapping it in a function where the page argument is the title of the page the user is navigating to and the callback will pass back the data returned from the getPageData function. When I try this it results in an undefined error for the callback of the pageContentLoaderfunction.

对于记录,下面代码中的 getPageData 是一个执行通用XMLHttpRequest的单独函数。它运行正常,因为数据在回调中被正确记录。

For the record, the getPageDatain the code below is a separate function which performs a generic XMLHttpRequest. It's working fine because the data gets logged correctly in the callback.

pageContentLoader(page, function(data) {
                    console.log("Back with data ", data);   
});

function pageContentLoader(page, callback){
    var data;

            switch (page) {
                case 'contact':
                    console.log('contact in switch');
                    getPageData(page,function(data){
                      console.log("Contacts back! ", data);     
                    });             
                    break;    
                case 'blog':
                    console.log('blog in switch');
                    getPageData(page,function(data){
                        console.log("Posts back! ", data);      
                    });                 
                    break;    
                default:
                    alert('hey that page doesn't exist!');    
            } 
            callback(data); // results in callback undefined!!
}   

我确信有可能做到这一点,但我已经尝试了一切到目前为止我找不到任何运气。如果有人有任何指示或想在我的代码中告诉我我做错了什么,我将不胜感激!

I am sure it is possible to make this work but I've tried everything I can find without any luck so far. If anyone has any pointers or wants to tell me what I am doing wrong within my code I'd be grateful!

推荐答案

这里是最近我改编的Typescript中的一个例子:

Here's a recent example in Typescript that I've adapted:

private pageContentLoader = async (): Promise<any> => {
    try {
        switch(page) {
            case 'contact':
                return await getPageData(page).then((data) => {
                    console.log("Contacts back! ", data);
                    return data;
                })
            case 'blog':
                return await getPageData(page).then((data) => {
                    console.log("Posts back! ", data);
                    return data;
                })
            default:
                return 'Page does not exist';
        }   
    } catch (err) {
        throw err;
    }
}


private getPageContent = async () => {
    try {
        const contactPageData = await pageContentLoader('contact');
        const blogPageData = await pageContentLoader('blog');
    } catch (err) {
        throw err;
    }
};

这篇关于在JavaScript开关/案例中做出承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆