如何检查承诺是否已解决以及有条件的呈现Javascript?

时间:2019-04-05 23:22:44

标签: javascript arrays ecmascript-6 promise

我的目标是呈现一个实时更新的“状态” UI,以指示已解决但仍待处理的每个服务,并呈现一个实时更新的“结果” UI,以指示每个服务。

目前,我有这段代码可与称为服务

的异步数据服务配合使用
const returnValues = [
    "Hakuna",
    "Matata",
    "It means",
    "No worries",
    "For the rest of your days"
].sort(() => (Math.random() > 0.5 ? 1 : -1));
const createService = (retVal, index) => () =>
    new Promise(resolve =>
        setTimeout(() => {
            console.log(`${index}. ${retVal}`);
            resolve(retVal);
        }, 
        Math.random() * 10000)
    );
const services = returnValues.map(createService);

我想有条件地呈现一个html模板,该模板将指示文本是否已解析

1 个答案:

答案 0 :(得分:2)

不能100%清楚所有UI交互应该是什么,但是类似以下内容可能会帮助您

const returnValues = [
  "Hakuna",
  "Matata",
  "It means",
  "No worries",
  "For the rest of your days"
].sort(() => (Math.random() > 0.5 ? 1 : -1));

const list = document.querySelector('#list');

const li =(txt)=>{
   const li = document.createElement('li');
   li.textContent = txt;
   return li
}


const createService = (retVal, index) => {
  const el = li(`${index+1} Pending...`);
  list.appendChild(el);
  return new Promise(resolve => {
    setTimeout(() => {     
      resolve(retVal);
    }, Math.random() * 5000)
  }).then(retVal=> {  el.textContent = `${retVal} ...Done`; return retVal})

};
const services = returnValues.map(createService);

Promise.all(services).then((allRetVals)=> list.appendChild(li('ALL DONE!')))
<ul id="list">

</ul>