美文网首页
13.promise的简单应用

13.promise的简单应用

作者: 最爱喝龙井 | 来源:发表于2019-09-26 19:25 被阅读0次

    有这么一个需求,有两个数组,我们要将第一个数组的name属性的值,换成第二个数组的对应的项的值,将name换成fullName

          var persons = [
                {name: 'jason', age: 18, hobbit:'sleep', id: 1},
                {name: 'jams', age: 20, hobbit: 'eat', id: 2}
            ];
            var owner = [
                {firstName: 'zhang', lastName: 'jason'},
                {firstName: 'li', lastName: 'jams1'}
            ];
    
    
            function findPerson(id) {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                        var person = persons.find(person => person.id == id);
                        if (person) {
                            resolve(person);
                        } else {
                            reject(Error('not find the person'))
                        }
                    }, 3000);
                })
            }
    
            function fullName(res) {
                return new Promise((resolve, reject) => {
                    setTimeout(() => {
                       var name = owner.find(name => name.lastName == res.name);
                       res.name = name;
                       if(name) {
                           resolve(res)
                       }else {
                           reject(Error('name is not found'))
                       } 
                    }, 3000);
                })
            }
    
            findPerson(2).then(data => fullName(data)).then(data => console.log(data))
    

    相关文章

      网友评论

          本文标题:13.promise的简单应用

          本文链接:https://www.haomeiwen.com/subject/vfdiyctx.html