在执行ajax调用后附加数据后调用方法

时间:2018-03-06 07:27:16

标签: javascript jquery ajax ecmascript-5

我有一个表名数组,所以我需要获取三个表的响应。请参阅以下代码。一旦数据被附加到dom我需要调用successMessage方法,现在我使用setTimeout如何在这种情况下使用promise

<script type="text/javascript" src="paintTiming.js"></script>
<script type="text/javascript">
    // should return object containing FP and FCP values    
    console.log(abc());
</script>

2 个答案:

答案 0 :(得分:1)

在显示消息之前,您必须使用Promise.all等待所有这些请求完成。首先,建立一个承诺数组:

var promises = lists.map(list => $.ajax({
    url:`${rootUrl}/api/('${list}')`,
    type: 'GET',
    headers: {
        accept: 'application/json'
         },
    success: res => dataDisplay(res),
    error: err => console.log(JSON.stringify(err))
}));

然后等待他们完成

Promise.all(promises).then(() => alert("data appended successfully"));

您也可以将$.when用于相同目的,但调用起来很尴尬:

$.when.apply($, promises).done(() => ...);

在评论中,您已经说dataDisplay加载了大量图片,您需要将调用延迟到successMessage,直到这些图片加载完毕为止。要做到这一点,您需要在图像上观察load事件。这可能有点松鼠,因为图像可以在您挂钩事件之前加载,因此我们也想要使用图像的complete标记。这些方面的东西:

Promises.all(/*...*/).then(() => {
    // Get all images in the tables we added to
    let imgs = $("#tbl1 img, #tbl2 img, #tbl3 img");

    // Hook up a function to check for completed images when we
    // see a `load` event on any of them, and fire that proactively
    imgs.on("load", checkComplete);
    checkComplete();

    function checkComplete() {
        // Count any incomplete images; remove the handler from any
        // complete image and remove it from our `imgs` set
        let incomplete = 0;
        imgs.get().forEach(img => {
            if (img.complete || img.error) {
                $(img).off("load", checkComplete);
                imgs = imgs.not(img);
            } else {
                ++incomplete;
            }
        });
        if (incomplete == 0) {
            // They're all done!
            successMessage();
       }
    }
});

这可能需要一些调整,但它应该让你以正确的方式前进。

答案 1 :(得分:-1)

您可以尝试以下代码:

let tableNames = ['table1', 'table2', 'table3']

let promiseArr = tableNames.map((table) => {
    return new Promise((resolve, reject) => {

        $.ajax({
            url:`${rootUrl}/api/('${list}')`,
            type: 'GET',
            headers: {
                accept: 'application/json'
                 },
            success: (res) => {
                dataDisplay(res);
                resolve(table);
            },
            error: (err) => {
                console.log(JSON.stringify(err));
                reject(table);
            }
          });
    }).catch((e) => {
        // if call to any of the table's url fails
        // it will come here, var 'e' contains
        // that table name, handle here
         console.log(e + " has fails"); return e; 
        });
});

Promise.all(promiseArr).
    then((result) => {
        // this will run regardless of, if call to any table fails 
        console.log("success") 
    })
    .catch((result) => {
        console.log(result + " fails");
    });

这将异步调用表,最后是Promise.all()的then(),即使调用某些表失败