异步/等待实现

时间:2020-06-13 09:07:01

标签: javascript promise async-await

我需要有关异步/等待实施的帮助。在我的代码中,我想要一个清除按钮以清除所有内容并重新加载页面。我想将其设置为一个承诺,以便仅在实现时才将获取请求发送到JSON服务器,并从JSON服务器获取帖子并将其存储在本地存储中。 我设置了一条console.log消息,当诺言解决时弹出。现在,我遇到的问题是出现此消息,并先获取数据,然后再进行页面重新加载。我认为页面重新加载将首先发生,然后才会出现该消息,并且将获取数据。这使代码无法正常运行。我不知道这是我建立Promise的方式。希望我的问题得到理解。有人帮忙,我保证要对您的答案和帐户进行投票:)

const UISelectors =uisetup.getSeletor(); //gets html classes and ids from another module
document.querySelector(UISelectors.clearBtn).addEventListener('click', clearAll); //calls event

const clearAllData = async function(){

    //This is the promise supposed to be waited on
    const clears = new Promise((resolve)=>{
        itemsetup.clearAll();
        uisetup.clearEverything()
        storagesetup.clearAllfromStorage()
        const addAllItems = 0
        uisetup.theTotaldatas(addAllItems)
        uisetup.clearEditState()
        location.reload()
        resolve('Finished clearing')
    })
    const storagedata = await clears
    return storagedata
}

//Function for the clear button event
function clearAll(e){
    e.preventDefault()

    //Calls the function after it has been completed
    clearAllData()
    .then(clearmessage=> {
        http.get('http://localhost:3000/posts')
        .then(posts => {
            storagesetup.storeinStorage(posts)
            uisetup.populateItems(posts)
            let datas=null
            posts.forEach(post =>{
            datas += post.datas
            })
            uisetup.theTotaldatas(datas)
            console.log(posts)
        })
        .catch(err=>console.log(err))
        console.log(clearmessage)

    })
}

1 个答案:

答案 0 :(得分:2)

通过查看下面的部分,我可以说您相信页面重新加载后,您的JS进程将恢复。

    location.reload()
    resolve('Finished clearing')

不是这样。反之亦然。也就是说,您创建了一个页面加载挂钩,该页面加载挂钩将在页面重新加载时执行,并在其中调用您的诺言,在诺言得到解决后采取任何措施。

<body onload="clearAll()">

让此函数获取数据并将其存储在本地存储中。您将需要相应地修改功能。